<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="formData">
        <a-form-item label="所属机构">
          <a-tree-select
            v-model:value="formData.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择所属机构"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="用户名称">
          <a-tree-select
            v-model:value="formData.nickName"
            tree-data-simple-mode
            allow-clear
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择操作人"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary">重置</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="showModal">新增</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        class="mt-5"
        :row-class-name="getRowClassName"
        :scroll="{ x: 2500, y: 550 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'passWord'">
            <template v-if="record.passWord">
              <a-space>
                <a>{{ record.passWord }}</a>
                <a-icon
                  :component="showPassWord ? EyeInvisibleOutlined : EyeOutlined"
                  @click="handleClick"
                />
              </a-space>
            </template>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button type="link" @click="handleEdit(record)">修改</a-button>
            <a-popconfirm
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              title="确认删除吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/修改用户弹窗 -->
    <a-modal
      :visible="modalVisible"
      :title="isEdit ? '修改人员信息' : '新增人员信息'"
      width="500px"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :model="userData" :label-col="labelCol">
        <a-form-item label="子公司">
          <a-tree-select
            v-model:value="userData.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择子公司"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="部门">
          <a-select v-model:value="userData.deptName" placeholder="请选择">
            <a-select-option value="生产部">生产部</a-select-option>
            <a-select-option value="财务部">财务部</a-select-option>
            <a-select-option value="收费部">收费部</a-select-option>
            <a-select-option value="法规部">法规部</a-select-option>
            <a-select-option value="主管领导">主管领导</a-select-option>
            <a-select-option value="业务主管">业务主管</a-select-option>
            <a-select-option value="经理">经理</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="用户名称">
          <a-input v-model:value="userData.userName" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input v-model:value="userData.passWord" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="userData.nickName" placeholder="请输入" />
        </a-form-item>

        <a-form-item label="用户编号">
          <a-input v-model:value="userData.userNumber" placeholder="请输入" />
        </a-form-item>

        <a-form-item label="手机号">
          <a-input v-model:value="userData.phoneNumber" placeholder="请输入" />
        </a-form-item>

        <a-form-item label="用户类型">
          <a-select v-model:value="userData.userType" placeholder="管理员">
            <a-select-option value="管理员">管理员</a-select-option>
            <a-select-option value="普通用户">普通用户</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="账号状态">
          <a-radio-group v-model:value="userData.status">
            <a-radio :value="0">已启用</a-radio>
            <a-radio :value="1">已禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input v-model:value="userData.idnumber" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getOperatorApi } from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import {
  getAccountList,
  getAddAccount,
  getUpdateAccount,
  getDeleteAccount,
} from '#/api/core/auth';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue';

const labelCol = { style: { width: '100px' } };
const showPassWord = ref(false);
onMounted(() => {
  getTableData();
});
const comanyList = ref<any[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    // console.log(comanyList.value);
  });
};
const selectList = ref<any[]>([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};

// 弹窗相关
const modalVisible = ref(false);
const isEdit = ref(false); // 是否为编辑模式
const currentEditId = ref(''); // 当前编辑的用户ID
const formData = reactive({
  comId: '',
  nickName: '',
});
const userData = reactive({
  userName: '', //用户名
  passWord: '', //密码
  phoneNumber: '', //手机号
  nickName: '', //昵称
  deptName: undefined, ///部门
  userNumber: '', //用户编号
  userType: '', //用户类型
  deleted: '', //是否删除
  status: '', // 账号状态（0正常 1停用）
  comId: undefined,
  idnumber: '', //身份证号
  comName: '', //公司名称
});
const showModal = () => {
  isEdit.value = false;
  resetUserData();
  modalVisible.value = true;
};

// 重置表单数据
const resetUserData = () => {
  Object.assign(userData, {
    userName: '',
    passWord: '',
    phoneNumber: '',
    nickName: '',
    deptName: undefined,
    userNumber: '',
    userType: '',
    deleted: '',
    status: '',
    comId: undefined,
    idnumber: '',
    comName: '',
  });
};

// 编辑用户
const handleEdit = (record: any) => {
  isEdit.value = true;
  currentEditId.value = record.id;
  // 填充表单数据
  Object.assign(userData, {
    userName: record.userName,
    passWord: record.passWord,
    phoneNumber: record.phoneNumber,
    nickName: record.nickName,
    deptName: record.deptName,
    userNumber: record.userNumber,
    userType: record.userType,
    deleted: record.deleted,
    status: record.status,
    comId: record.comId,
    idnumber: record.idnumber,
    comName: record.comName,
  });
  modalVisible.value = true;
};

const handleOk = () => {
  if (isEdit.value) {
    // 修改用户
    const updateData = { ...userData, id: currentEditId.value };
    getUpdateAccount(updateData)
      .then((res: any) => {
        if (res.data.code == 200) {
          message.success('修改成功');
          onSearch();
          modalVisible.value = false;
        } else {
          message.error('修改失败');
        }
      })
      .catch(() => {
        message.error('修改失败');
      });
  } else {
    // 新增用户
    getAddAccount(userData)
      .then((res: any) => {
        if (res.data.code == 200) {
          message.success('新增成功');
          onSearch();
          modalVisible.value = false;
        } else {
          message.error('新增失败');
        }
      })
      .catch(() => {
        message.error('新增失败');
      });
  }
};

const handleCancel = () => {
  modalVisible.value = false;
  resetUserData();
  isEdit.value = false;
  currentEditId.value = '';
};

const columns = [
  {
    title: '用户名称',
    dataIndex: 'userName',
    key: 'userName',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    key: 'nickName',
    align: 'center',
  },
  // {
  //   title: '密码',
  //   dataIndex: 'passWord',
  //   key: 'passWord',
  //   align: 'center',
  // },
  {
    title: '部门',
    dataIndex: 'deptName',
    key: 'deptName',
    align: 'center',
  },
  {
    title: '用户编号',
    dataIndex: 'userNumber',
    key: 'userNumber',
    align: 'center',
  },
  {
    title: '手机号',
    dataIndex: 'phoneNumber',
    key: 'phoneNumber',
    align: 'center',
  },
  {
    title: '用户类型',
    dataIndex: 'userType',
    key: 'userType',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '账号状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center',
  },
  {
    title: '子公司',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'createName',
    key: 'createName',
    align: 'center',
  },
  {
    title: '身份证号',
    dataIndex: 'idnumber',
    key: 'idnumber',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    fixed: 'right',
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    comId: formData.comId,
    nickName: formData.nickName,
  };
  getAccountList(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data;
    pagination.total = res.data.total;
  });
};
const handleClick = (record: any) => {
  showPassWord.value = !showPassWord.value;
};

// 表格行类名函数
const getRowClassName = (record: any, index: number) => {
  return index % 2 === 1 ? 'table-striped' : null;
};
const handleDelete = (e: any) => {
  console.log(e);
  getDeleteAccount(e.id).then((res: any) => {
    console.log(res);
    if(res.data.code==200){
      message.success('删除成功');
      onSearch();
    }else{
      message.error('删除失败');
    }
  });
};
</script>
<style scoped></style>
